package com.thuanhoang.boo;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import thirdparty.HorizontalListView;
import util.Constant;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.boo.service.StoreService;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.thuanhoang.boo.adapter.MerchantListAdapter;
import com.thuanhoang.boo.model.Merchant;
import com.thuanhoang.boo.model.Store;

public class MapActivity  extends FragmentActivity{
	private static ArrayList<Store> storeList;
	private ArrayList<Merchant> merchantList;
	// Google Map
	private GoogleMap googleMap;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
		showLoading() ;
		merchantList = HomeActivity.merch_list;
		googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
		storeList = new ArrayList<Store>();

		HorizontalListView listMerchant = (HorizontalListView) findViewById(R.id.listMerchant);
		listMerchant.setAdapter(new MerchantListAdapter(this,merchantList));
		listMerchant.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Merchant merchant = merchantList.get(position);
				ProductListActivity.merchant = merchant;
				Intent intent = new Intent(MapActivity.this,ProductListActivity.class);
				startActivity(intent);
			}

		});
		getStore();
		initAction();
	}

	private void initAction() {
		View btnChannel =(View) findViewById(R.id.btn_magazine);
		btnChannel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MapActivity.this,ChannelActivity.class);
				startActivity(intent);

			}
		});
		
		View btnAccount = (View)findViewById(R.id.btn_account);
		btnAccount.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MapActivity.this, UpdateInfoActivity.class));
			}
		});
		// TODO Auto-generated method stub
		
	}

	public void showLoading() {
		findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
	}

	public void hiddenLoading() {
		findViewById(R.id.loadingPanel).setVisibility(View.GONE);
	}
	public void getStore(){
		StoreService storeService = new StoreService(this);

		// get user history by using email
		storeService.getData(Constant.API_GET_STORE_URL);
	}
	public void afterStore(JSONObject response){
		ArrayList<Store> storeTmp = new ArrayList<Store>();
		try {
			Log.d("Store", " get ok");
			JSONArray listStore = response.getJSONArray("Stores");
			if(listStore!=null){
				Gson gson = new Gson();
				for (int i = 0; i < listStore.length(); i ++){
					JSONObject memberJsonInfo = listStore.getJSONObject(i);
					String stringInfo = memberJsonInfo.toString();
					Store newStore = gson.fromJson(stringInfo, Store.class);
					storeTmp.add(newStore);
				}
				if(storeList.size()>0 && storeList.size() == storeTmp.size()){ // should deep compare is better!
					Log.e("Cache", "Not need reload");
					return;
				}
				storeList.clear();
				for(Store store: storeTmp){
					storeList.add(store);
				}
				initilizeMap();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * function to load map. If map is not created it will create it for you
	 * */
	@SuppressLint("NewApi")
	private void initilizeMap() {
		if(googleMap ==null){
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();
		}

		// check if map is created successfully or not
		if (googleMap == null) {
			Toast.makeText(getApplicationContext(),
					"Sorry! Unable to create maps", Toast.LENGTH_SHORT)
					.show();
		} else {
			try{
				for(int i =0;i<storeList.size();i++){
					double longitude = Double.parseDouble(storeList.get(i).getLongitude());
					double latitude = Double.parseDouble(storeList.get(i).getLatitude());
					String shop_name = storeList.get(i).getStoreName();
					//Log.d("shop name", "is " + shop_name);
					googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))
							.title(shop_name));

				}
				LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				Location location = locationManager
						.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				if (location == null) {
					location = locationManager
							.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				}
				if (location==null) {
					Criteria crit = new Criteria();
					crit.setAccuracy(Criteria.ACCURACY_FINE);
					String provider = locationManager.getBestProvider(crit, true);
					location = locationManager.getLastKnownLocation(provider);
				}
				if(location ==null){
					double longitude = Double.parseDouble(storeList.get(0).getLongitude());
					double latitude = Double.parseDouble(storeList.get(0).getLatitude());
					googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))
							.icon(BitmapDescriptorFactory
						              .fromResource(R.drawable.my_location)));
					googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
				}
				else{
					googleMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude()))
							.icon(BitmapDescriptorFactory
						              .fromResource(R.drawable.my_location)));
					googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15));
				}

				// Zoom in, animating the camera.
				googleMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
				googleMap.getUiSettings().setMyLocationButtonEnabled(true);
				googleMap.getUiSettings().setCompassEnabled(true);
				googleMap.getUiSettings().setZoomGesturesEnabled(true);
				hiddenLoading();
			}
			catch (Exception e) {
				hiddenLoading();
				Log.e("error", "is " + e.getMessage());
			}				
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		//initilizeMap();
	}

}
